package com.test.nnooolwdeaer.util_wooden.event

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import com.test.nnooolwdeaer.constant_wooden.Constant_wooden

class TrackEventRepository_wooden(context: Context) {
    private val dbHelper = TrackDatabase_wooden(context)

    fun insertEvent(event: TrackEvent_wooden): Long {
        try {
            val db = dbHelper.writableDatabase
            val values = ContentValues().apply {
                put("type", event.type)
                put("remark", event.remark)
                put("createTime", event.createTime)
                put("isUpload", if (event.isUpload) 1 else 0)
            }
            return db.insert("track_event", null, values)
        } catch (e: Exception) {
            if (Constant_wooden.Debug) e.printStackTrace()
        }
        return 0
    }

    fun getUnUploadedEvents(): List<HashMap<String, String>> {
        val events = mutableListOf<HashMap<String, String>>()
        try {
            val db = dbHelper.readableDatabase
            val cursor: Cursor = db.rawQuery("SELECT * FROM track_event WHERE isUpload = 0", null)
            with(cursor) {
                while (moveToNext()) {
                    val eve = hashMapOf<String, String>().apply {
                        put("id", getString(getColumnIndexOrThrow("id")))
                        put("type", getString(getColumnIndexOrThrow("type")))
                        put("remark", getString(getColumnIndexOrThrow("remark")))
                        put("timestamp", getString(getColumnIndexOrThrow("createTime")))
                    }
                    events.add(eve)
                }
            }
            cursor.close()
        } catch (e: Exception) {
            if (Constant_wooden.Debug) e.printStackTrace()
        }
        return events
    }

    fun markAsUploaded(ids: List<Long>): Int {
        try {
            if (ids.isEmpty()) return 0
            val db = dbHelper.writableDatabase
            val args = ids.joinToString(",")
            return db.execSQL("UPDATE track_event SET isUpload = 1 WHERE id IN ($args)").let { 1 }
        } catch (e: Exception) {
            if (Constant_wooden.Debug) e.printStackTrace()
        }
        return 0
    }

    fun deleteUploadedEvents(): Int {
        try {
            val db = dbHelper.writableDatabase
            return db.delete("track_event", "isUpload = 1", null)
        } catch (e: Exception) {
            if (Constant_wooden.Debug) e.printStackTrace()
        }
        return 0
    }

    fun close() {
        try {
            dbHelper.close()
        } catch (e: Exception) {
            if (Constant_wooden.Debug) e.printStackTrace()
        }
    }
}
